import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Home-pc
 * Date: 2023-10-19
 * Time: 20:04
 */
@WebServlet("/request")
public class RequestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 下面这个操作也是必要的. 显式告诉浏览器, 你拿到的数据是 html.
        resp.setContentType("text/html");
        StringBuilder respBody=new StringBuilder();

        respBody.append(req.getProtocol());
        //使用 <br> 标签表示换行
        respBody.append("<br>");
        respBody.append(req.getMethod());
        respBody.append("<br>");
        respBody.append(req.getRequestURI());
        respBody.append("<br>");
        respBody.append(req.getContextPath());
        respBody.append("<br>");
        respBody.append(req.getQueryString());
        respBody.append("<br>");

        //Enumeration 枚举类型，每一个枚举类型都是一个键值对，即headers中包含多个键值对
        Enumeration<String> headers=req.getHeaderNames();
        while(headers.hasMoreElements()){//一开始的时候，并不指向第一个键值对的name
            String header= headers.nextElement();//指向第一个键值对的name
            respBody.append(header + ": "+req.getHeader(header));//getHeader:获取键值对的值
            respBody.append("<br>");
        }
        resp.getWriter().write(respBody.toString());
    }
}
